package com.itheima.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component      //合适的时机被创建
public class TokenInterceptor implements HandlerInterceptor {

//    1.重写其preHandle方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.省略强转，省略login路径的拦截


//        2.校验Token,第一步看有没有Token
        String jwt = request.getHeader("token");        //不区分大小写，token和Token都行


//        3.为空响应401
        if(StrUtil.isEmpty(jwt)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);     //报错，返回401
            return false;
        }

//        4.不为空校验,错了抛异常，没错登陆成功
        try {
            JwtUtils.parseJWT(jwt);
            return true;                            //放行,加入Controller层
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);         //报错，返回401
            return false;
        }
    }


}
